// socket.io specific code

var socket = io.connect("/chat");//, resource:"chat");

var socket_game = io.connect("/game");//, resource:"chat");

socket.on('connect', function () {
    $('#chat').addClass('connected');
    socket.emit('join', window.room); 
});

socket_game.on('connect', function () {
    //$('#chat').addClass('connected');
    console.log("socket_game conectado");
    socket_game.emit('join', window.game);
});


socket.on('announcement', function (msg) {
    $('#lines').append($('<p>').append($('<em>').text(msg)));
});


socket_game.on('exception', function(msg){
    alert('Exception: ' + msg);
});


socket_game.on('players', function (players_names, players_points) {
    console.log('Actualizando players..');
    $('#players').empty();

    // Selection Sort n^2: Provisional
    for (var i=0; i<players_points.length-1; i++) {
        var mini = i;
        for(var j = i+1; j<players_points.length; j++){
            if(players_points[mini] < players_points[j]) mini = j;
        }
        var tmp = players_points[mini];
        players_points[mini] = players_points[i];
        players_points[i] = tmp;

        var tmp2 = players_names[mini];
        players_names[mini] = players_names[i];
        players_names[i] = tmp2;
    }

    for (var i in players_names) {
	  $('#players').append($('<div>').text(players_names[i] + " - " + players_points[i]));
    }
});


socket_game.on('map', function(players_id, players_name, x_coordinates, y_coordinates){
    console.log('Actualizando mapa...');
    // map_x_y --> map_x_y_id
    for (var i=0; i<players_id.length; i++) {
        if ($('#map_' + x_coordinates[i] + '_' + y_coordinates[i]).length == 1) {
            $('#map_' + x_coordinates[i] + '_' + y_coordinates[i]).attr('id', 'map_' + x_coordinates[i] + '_' + y_coordinates[i] + '_' + players_id[i]);
            $('#map_' + x_coordinates[i] + '_' + y_coordinates[i] + '_' + players_id[i]).children('.name').html(players_name[i]);
            $('#map_' + x_coordinates[i] + '_' + y_coordinates[i] + '_' + players_id[i]).children('.actions').children('.send-resources').attr('id', 'send_resources_' + players_id[i]);
        }
    }

});


function probando(){
    this.remove();
}

/*
    Update the event times
    Type Events:
        - Start Resource (resource_start)
        - Back Resource (resource_back)
        - Finish Resource (resource_finish)

        - Start Attack (attack_start)
        - Back Attack (attack_back)
        - Finish Attack (attack_finish)
*/
socket_game.on('time_event', function(id_event, type_event, seconds){
    console.log('Actualizando eventos de tiempo...');
    
    // Añadir ordenados por tiempo de llegada...
    date = new Date();
    date.setSeconds(date.getSeconds() + parseInt(seconds));
    
    if (type_event == 'resource_start'){
        $('#time_events').append($('<div>').attr('id', type_event + '_' + id_event ).html('Enviando Recursos...'));
        $('#' + type_event + '_' + id_event).countdown({
            until: date,
            onExpiry: probando,
        });
    } else if (type_event == 'resource_back') {
        $('#time_events').append($('<div>').attr('id', type_event + '_' + id_event).html('Llegando Recursos...'));
        $('#' + type_event + '_' + id_event).countdown({
            until: date,
            onExpiry: probando,
        });
    } 
    else {
        alert('No conozco el tipo de evento...');
    }
});


// vector ordenado por bases.id
socket_game.on('resources', function(num_resources){
    console.log('Actualizando recursos...');
    $('#resources').html(parseInt(num_resources));
});


socket_game.on('ants', function(ants_types, ants_nums){
    console.log('Actualizando ejército...');
    $('#ants').empty();

    for (var i in ants_types) {
	  $('#ants').append($('<div>').text(ants_types[i] + " - " + ants_nums[i]));
    }

});


socket.on('nicknames', function (nicknames) {
    $('#nicknames').empty().append($('<span>Online: </span>'));
    // ordenar nicknames por 'points'
    for (var i in nicknames) {
	  $('#nicknames').append($('<b>').text(nicknames[i]));
    }

});

socket.on('msg_to_room', message);

socket.on('reconnect', function () {
    $('#lines').remove();
    message('System', 'Reconnected to the server');
});

socket.on('reconnecting', function () {
    message('System', 'Attempting to re-connect to the server');
});

socket.on('error', function (e) {
    message('System', e ? e : 'A unknown error occurred');
});

function message (from, msg) {
    $('#lines').append($('<p>').append($('<b>').text(from), msg));
}

function new_ant(type_ant){
    socket_game.emit('new_ant', type_ant, function(set){
        if(set){
            // actualizar aquí el ejército...???
            console.log("Hormiga creada con éxito!");
            return false;
        }else{
            alert("Problemas  al crear la hormiga...");
        }
    });
}

// DOM manipulation
$(function () {
    $('#set-nickname').submit(function (ev) {

        socket.emit('nickname', $('#nick').val(), function (set) {
            if (set) {
                clear();
                return $('#chat').addClass('nickname-set');
            }
            $('#nickname-err').css('visibility', 'visible');
        });

        // GAME
        socket_game.emit('nickname', $('#nick').val(), function (set){
            if(set){
                //Cosas que hacer tras la conexión ...
                console.log("probando"  + set);
            } else {
                // otros errores...
                alert("Problemas, no hemos podido conectar con el socket game.");
            }
        });
        
        return false;
    });

    $('#send-message').submit(function () {
	    message('me', $('#message').val());
	    socket.emit('user message', $('#message').val());
	    clear();
	    $('#lines').get(0).scrollTop = 10000000;
	    return false;
    });


    $('.send-resources').submit(function () {
        player_id = $(this).attr('id').split('_')[2];
        resources = $(this).children('.resources').val();
        socket_game.emit('movement_resources', player_id, resources);
        $(this).children('.resources').val('');
	    return false;
    });

    function clear() {
        $('#message').val('').focus();
    };
    
});



